import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import api from '@/utils/api';

interface User {
  id: number;
  username: string;
  role: 'user' | 'mechanic' | 'admin';
}

interface Credentials {
  username: string;
  password: string;
}

interface RegisterData extends Credentials {
  confirmPassword?: string;
}

interface AuthResponse {
  token: string;
  user: User;
}

export const useAuthStore = defineStore('auth', () => {
  const token = ref('');
  const user = ref<User | null>(null);
  const router = useRouter();

  // Initialize from localStorage
  const storedToken = localStorage.getItem('token');
  const storedUser = localStorage.getItem('user');
  if (storedToken) token.value = storedToken;
  if (storedUser) {
    try {
      user.value = JSON.parse(storedUser);
    } catch {
      user.value = null;
    }
  }

  const isAuthenticated = computed(() => !!token.value);

  const login = async (credentials: Credentials): Promise<AuthResponse> => {
    try {
      const response = await api.post<AuthResponse>('/auth/login', credentials);
      token.value = response.token;
      user.value = response.user;
      
      localStorage.setItem('token', token.value);
      localStorage.setItem('user', JSON.stringify(user.value));
      
      return response;
    } catch (error) {
      throw error;
    }
  };

  const logout = (): void => {
    token.value = '';
    user.value = null;
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    router.push('/login');
  };

  const register = async (userData: RegisterData): Promise<AuthResponse> => {
    try {
      const response = await api.post<AuthResponse>('/auth/register', userData);
      return response;
    } catch (error) {
      throw error;
    }
  };

  return {
    token,
    user,
    isAuthenticated,
    login,
    logout,
    register
  };
});
